<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Shop\Form\HomeUserEditAvatarForm;
use Shop\Form\HomeUserEditForm;
use User\Entity\User;
use User\Entity\UserOtherLogin;
use User\Service\UserManager;
use User\Service\UserNameLogManager;
use User\Service\UserOtherLoginManager;

class HomeUserController extends HomeActionController
{
    private $translator;
    private $writeEntityManager;
    private $userManager;
    private $userOtherLoginManager;
    private $userNameLogManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $writeEntityManager,
        UserManager     $userManager,
        UserOtherLoginManager $userOtherLoginManager,
        UserNameLogManager $userNameLogManager
    )
    {
        $this->translator           = $translator;
        $this->writeEntityManager   = $writeEntityManager;
        $this->userManager          = $userManager;
        $this->userOtherLoginManager= $userOtherLoginManager;
        $this->userNameLogManager   = $userNameLogManager;
    }

    /**
     * 资料修改
     * @return array|\Laminas\Http\Response|\Laminas\View\Model\ViewModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('资料修改'));

        $userInfo = $this->writeEntityManager->getRepository(User::class)->findOneBy(['userId' => parent::$userId]);

        $form = new HomeUserEditForm($this->writeEntityManager, $userInfo);
        $form->get('userSex')->setValueOptions(Common::userSex($this->translator));

        //是否允许修改登录账户名称
        $loginAccountEditState = Common::configValue('login_account_edit', 'customer');

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                if ($loginAccountEditState == 1 && !empty($data['userName']) && $data['userName'] != $userInfo->getUserName()) {
                    $this->userNameLogManager->addUserNameLog([
                        'editUserName'  => $userInfo->getUserName(),
                        'editTime'      => time(),
                        'userId'        => parent::$userId
                    ]);
                    $userInfo = $this->userManager->changeUserName($data['userName'], $userInfo);
                }

                $this->userManager->editUser($data, $userInfo);

                $this->flashMessenger()->addSuccessMessage($this->translator->translate('资料修改完成!'));
                return $this->redirect()->toRoute('home-user');
            }
        } else $form->setData($userInfo->valuesArray());

        return [
            'form'      => $form,
            'userInfo'  => $userInfo,
            'loginAccountEditState' => $loginAccountEditState
        ];
    }

    /**
     * 头像设置
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAvatarAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('头像设置'));

        $userInfo = $this->writeEntityManager->getRepository(User::class)->findOneBy(['userId' => parent::$userId]);

        $form = new HomeUserEditAvatarForm($userInfo);
        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $userAvatar = $userInfo->getUserAvatar();
                $this->userManager->editUser($data, $userInfo);

                $this->getEventManager()->trigger('shop.user.edit.post', $this, ['user' => $userInfo, 'data' => $data, 'userAvatar' => $userAvatar]);

                $this->flashMessenger()->addSuccessMessage($this->translator->translate('头像修改完成!'));
                return $this->redirect()->toRoute('home-user', ['action' => 'editAvatar']);
            }
        }

        $form->setData($userInfo->valuesArray());

        return ['form' => $form, 'userInfo' => $userInfo];
    }

    /**
     * 账户绑定
     * @return array
     */
    public function accountBindAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('账户绑定'));

        $userOtherLogin = $this->writeEntityManager->getRepository(UserOtherLogin::class)->findBy(['userId' => parent::$userId]);
        $bindUserLogin  = [];
        if ($userOtherLogin) foreach ($userOtherLogin as $value) {
            $bindUserLogin[] = $value->getLoginType();
        }

        //第三方绑定名称
        $otherLoginTextName = Common::otherLoginTextName($this->translator);

        //账户绑定项
        $enableLogin = $this->shopPlugin()->enableOtherLogin();

        return ['bindUserLogin' => $bindUserLogin, 'enableLogin' => $enableLogin, 'otherLoginTextName' => $otherLoginTextName];
    }

    /**
     * 删除绑定
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAccountBindAction()
    {
        $loginType      = $this->params()->fromRoute('id', -1);
        $userOtherLogin = $this->writeEntityManager->getRepository(UserOtherLogin::class)->findOneBy(['loginType' => $loginType, 'userId' => parent::$userId]);
        if ($userOtherLogin == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('删除失败，该绑定不存在!'));
            return $this->redirect()->toRoute('home-user', ['action' => 'accountBind']);
        }

        $this->userOtherLoginManager->deleteUserOtherLogin($userOtherLogin);

        $this->flashMessenger()->addSuccessMessage($this->translator->translate('账户解绑成功!'));
        return $this->redirect()->toRoute('home-user', ['action' => 'accountBind']);
    }
}